package han.fetch;

import han.entity.FinanceProjectInfoEntity;
import han.parser.Regex;
import han.sql.Operator;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.han.http.util.Print.printlnInfo;

/**
 * @author: Han
 * @date: 2018/7/13 9:07
 * @dscription: 信息补充类
 */
public class InfoSupplementer {

    public static void main(String... args) {
        Operator operator = Operator.getInstance();
        List<FinanceProjectInfoEntity> infoEntityList = operator.queryProjectInfoByCondition(2);
        Random random = new Random();
        for (FinanceProjectInfoEntity infoEntity : infoEntityList) {
            int interval = random.nextInt(1000 * 10) + 1000 * 5;
            String name = infoEntity.getFullName();
            name = "-".equals(infoEntity.getFullName()) ? infoEntity.getName() : name;
            try {
                //如果名称中包含5个以上英文字符,则不查询此公司
                boolean areYouOk = name.matches("[a-zA-Z0-9\\s.'_+/*~!]{5,1000}");
                if (areYouOk) {
                    interval = 0;
                    infoEntity.setEmail("-");
                    infoEntity.setPhoneNumber("-");
                    infoEntity.setAddress("-");
                    operator.updateFinanceProjectInfo(infoEntity);
                    printlnInfo(name + "跳过");
                    continue;
                }
                String[] contact = InfoSupplementer.qiChaCha(name, "QCCSESSID=out2f87fm430mkab1vvplftv42; UM_distinctid=16660a8e652228-02b15d64fe0333-6155742c-1fa400-16660a8e6537a7; CNZZDATA1254842228=911885405-1539219436-https%253A%252F%252Fwww.baidu.com%252F%7C1539219436; Hm_lvt_3456bee468c83cc63fb5147f119f1075=1539219974; hasShow=1; _uab_collina=153921997422623574308846; acw_tc=debab7a215392199763024485e705ef0ef52cf2057b32c3ad80567d147; _umdata=A502B1276E6D5FEF4F7F6C9FC888D00ABB7960993597B7A962E25B703377099B7757748D1CE4DB23CD43AD3E795C914C8CE88E56027419D7F72CB08DEA46CF04; QCCSESSID=out2f87fm430mkab1vvplftv42; Hm_lpvt_3456bee468c83cc63fb5147f119f1075=1539220035");
                infoEntity.setEmail(contact[0]);
                infoEntity.setPhoneNumber(contact[1]);
                infoEntity.setAddress(contact[2]);
                printlnInfo(name + "信息补充成功");
            } catch (Exception e) {
                printlnInfo(name + "信息补充失败:" + e.getMessage());
                infoEntity.setEmail("-");
                infoEntity.setPhoneNumber("-");
                infoEntity.setAddress("-");
            } finally {
                operator.updateFinanceProjectInfo(infoEntity);
                try {
                    Thread.sleep(interval);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String[] qiChaCha(String companyName, String cookie) throws Exception {
        companyName = companyName.replace(" ", "%20");
        String urlStr = "https://www.qichacha.com/search?key=" + companyName;
        Map<String, String> requestHeaders = new HashMap<>();
        requestHeaders.put("%0aauthority", "www.qichacha.com");
        requestHeaders.put("%0amethod", "GET");
        requestHeaders.put("%0apath", "/search?key=" + companyName);
        requestHeaders.put("%0ascheme", "https");
        requestHeaders.put("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        requestHeaders.put("accept-encoding", "gzip, deflate, br");
        requestHeaders.put("accept-language", "zh-CN,zh;q=0.9");
        requestHeaders.put("cookie", cookie);
        requestHeaders.put("referer", "https://www.qichacha.com/");
        requestHeaders.put("upgrade-insecure-requests", "1");
        requestHeaders.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36");
        String[] contact = {"-", "-", "-"};
        Connection connection = Jsoup.connect(urlStr);
        connection.headers(requestHeaders);
        connection.timeout(1000 * 30);
        Document document = connection.get();
        Element element1 = document.getElementsByClass("m_srchList").first();
        Element element2 = element1.getElementsByTag("tbody").first();
        Element element3 = element2.getElementsByTag("tr").first();
        Elements elements = element3.getElementsByClass("m-t-xs");
        String ep = elements.get(1).text();
        contact[0] = Regex.matchString(ep, "(?<=邮箱：).*.com");
        contact[1] = Regex.matchString(ep, "(?<=电话：)[-\\d]*");
        contact[2] = Regex.matchString(elements.get(2).text(), "(?<=地址：)((?!\\s).*)").replaceAll("<((?!>).)*>", "");

        return contact;
    }
}
